package com.sx.pipeline.ui.chat.search

import android.net.Uri
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.lxj.xpopup.XPopup
import com.sx.mvvmlibs.base.EasyAdapter
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.adapter.SearchContactAdapter
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.ActivityContactSearchBinding
import com.sx.pipeline.repos.http.res.ContactUserVo
import com.sx.pipeline.repos.http.res.RongGroupVO
import com.sx.pipeline.ui.chat.ChatVM
import com.sx.pipeline.utils.AndroidUtil
import io.rong.imkit.RongIM


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 点对点通讯/搜索
 */
@Route(path = RoutePath.Chat.CHAT_SEARCH)
class SearchContactActivity : CYDataBindingBaseActivity<ActivityContactSearchBinding, ChatVM>(
    com.sx.pipeline.R.layout.activity_contact_search
), View.OnClickListener {
    @JvmField
    @Autowired(name = IntentKey.TYPE)
    var type: Int? = 0  //0 单选  1多选

    private var isSelectAll = false //默认未全选
    private var userIdList: MutableList<String> = ArrayList() //用户id集合

    private lateinit var mAdapter: SearchContactAdapter
    private var key = ""

    override fun initData() {
        super.initData()
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.title=mViewModel.mModel.getUserData()?.unitName
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        mViewModel.getRongContact(key)
    }

    private fun initRv(serviceList: List<ContactUserVo>) {
        mAdapter = SearchContactAdapter(this, type, serviceList)
        mBinding.recyclerView.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mBinding.recyclerView.setAdapter(mAdapter)
        if (serviceList.size != 0) {
            mBinding.recyclerView.visibility = View.VISIBLE
            mBinding.emptyView.visibility = View.GONE
        } else {
            mBinding.recyclerView.visibility = View.GONE
            mBinding.emptyView.visibility = View.VISIBLE
        }
        if (type == 0) {
            mBinding.tabAll.visibility = View.GONE
            mAdapter.setSelectMode(EasyAdapter.SelectMode.SINGLE_SELECT)
            mAdapter.setOnItemSingleSelectListener { itemPosition, isSelected ->
                ARouter.getInstance().build(RoutePath.Chat.CHAT_PERSONAL)
                    .withInt(IntentKey.ID, serviceList[itemPosition].userUnitId).navigation()
            }
        } else {
            mBinding.tabAll.visibility = View.VISIBLE
            mAdapter.setSelectMode(EasyAdapter.SelectMode.MULTI_SELECT)
            mAdapter.setOnItemMultiSelectListener { operation, itemPosition, isSelected ->

            }
        }


    }


    override fun initViewObservable() {
        super.initViewObservable()

        mViewModel.contactListEvent.observe(this) {
            it?.let { it1 -> initRv(it1) }
        }

        //群聊创建成功
        observe(mViewModel.groupSuccessEvent){
            if (it==true){
                mViewModel.getRongGroupList()
            }
        }

        observe(mViewModel.groupListEvent) {
            if (it != null) {
                refreshRongGroupInfo(it)
            }
        }
    }

    override fun initListener() {
        super.initListener()
        mBinding.etKeyword.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(
                s: CharSequence,
                start: Int,
                before: Int,
                count: Int
            ) {

            }

            override fun beforeTextChanged(
                s: CharSequence,
                start: Int,
                count: Int,
                after: Int
            ) {

            }

            override fun afterTextChanged(s: Editable) {
                key = mBinding.etKeyword.text.toString()
                mViewModel.getRongContact(key)
            }
        })
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            //组织架构
            R.id.cb_all -> {
                if (isSelectAll == false) {
                    isSelectAll = true
                    mBinding!!.cbAll.isSelected = true
                    mAdapter?.selectAll()
                } else {
                    isSelectAll = false
                    mBinding!!.cbAll.isSelected = false
                    mAdapter?.clearSelected()
                }
            }
            //提交创建群聊
            R.id.tv_commit -> {
                userIdList.clear()
                if (mAdapter.multiSelectedPosition.size == 0) {
                    ToastUtils.showShort("请选择联系人")
                    return
                }
                for (i in mAdapter?.multiSelectedPosition!!) {
                    userIdList.add(mViewModel.contactListEvent.value!![i].userUnitId.toString())
                }
                XPopup.Builder(this)
                    .hasStatusBarShadow(false) //.dismissOnBackPressed(false)
                    .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .autoOpenSoftInput(true)
                    .isViewMode(true) //                        .setPopupCallback(new DemoXPopupListener())
                    //                        .autoFocusEditText(false) //是否让弹窗内的EditText自动获取焦点，默认是true
                    //.moveUpToKeyboard(false)   //是否移动到软键盘上面，默认为true
                    .asInputConfirm(
                        "温馨提示", null, null, "请输入群聊名称"
                    ) {
                        if (TextUtils.isEmpty(it)) {
                            ToastUtils.showShort("请输入群聊名称")
                            return@asInputConfirm
                        }
                        mViewModel.getCreateGroup(1, it, userIdList)
                    }
                    .show()
            }
        }
    }


    private fun refreshRongGroupInfo(friendList: List<RongGroupVO>) {
        //融云IM -> 刷新群组信息
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val group = io.rong.imlib.model.Group(
                friendList[i].id,
                friendList[i].name,
                Uri.parse("")
            )
            //通过网络请求动态加载群信息

            //通过网络请求动态加载群信息
            RongIM.getInstance().refreshGroupInfoCache(group)
            Logs.d("re缓存群聊信息成功：" + group)
        }
    }
}